package com.example.caorl.jdbc.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtil {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    private JDBCUtil() {
    }

    static {
        try {
            //ClassLoader loader=Thread.currentThread().getClass().getClassLoader();
            ClassLoader loader = JDBCUtil.class.getClassLoader();
            InputStream in = loader.getResourceAsStream("db.properties");
            Properties p = new Properties();
            p.load(in);//加载必须在调用之前

            driver = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");
            //System.out.println(driver);
            in.close();
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //解决硬编码
    }

    /**
     * 用于获取连接数据库的对象
     *
     * @return Connection对象
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        return DriverManager.getConnection(url, username, password);
    }

    //在这个方法中，产生的异常可以try/catch

    /**
     * close()方法用于关闭数据库连接过程中出现的一些资源
     */
    public static void close(Connection conn, Statement st, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (st != null) {
                st.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection conn) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void reset(Connection conn) {
        try {
            if (conn!=null) {
                conn.setAutoCommit(true);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
